package com.baox.agridata.synchronous.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.input.ReversedLinesFileReader;

import java.io.*;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
public class FileUtil {

    public String getPath() {
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if (System.getProperty("os.name").contains("dows")) {
            path = path.substring(1, path.length());
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            return path.substring(0, path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }

    public String readLastLineV2(String filePath, String fileName) {
        String lastLine = "";

        String fullPath = filePath + File.separator + fileName;
        File file = new File(fullPath);

        try (ReversedLinesFileReader reversedLinesReader = new ReversedLinesFileReader(file, Charset.defaultCharset())) {
            lastLine = reversedLinesReader.readLine();
        } catch (Exception e) {
            log.error("file read error, msg:{}", e.getMessage(), e);
            e.printStackTrace();
        }
        return lastLine;
    }

    /**
     * 检查路径和文件是否存在
     *
     * @param filePath
     * @param fileName
     * @return
     */
    public Boolean CheckFileExists(String filePath, String fileName) {
        Boolean isExists = false; //默认不存在

        File pathFile = new File(filePath);
        if (pathFile.exists()) { //判断文件夹是否存在
            String fullPath = filePath + File.separator + fileName;
            File file = new File(fullPath);
            if (file.exists()) {
                isExists = true;
            }
        }
        return isExists;
    }

    public boolean WriteContent(String content, String filePath, String fileName) {
        // 标记文件生成是否成功
        boolean flag = true;
        try {
            File pathFile = new File(filePath);
            if (!pathFile.exists()) { //如果文件夹不存在，则创建文件夹
                pathFile.mkdirs();
            }
            // 含文件名的全路径
            String fullPath = filePath + File.separator + fileName;
            File file = new File(fullPath);
            if (!file.exists()) { // 如果已存在,删除旧文件
                file = new File(fullPath);
                file.createNewFile();
            }
            // 格式化浮点数据
            NumberFormat formatter = NumberFormat.getNumberInstance();
            formatter.setMaximumFractionDigits(10); // 设置最大小数位为10

            // 遍历输出每行
            PrintWriter pfp = new PrintWriter(file, "UTF-8"); //设置输出文件的编码为utf-8
            pfp.print(content);
            pfp.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    public boolean createStringFile(List<String> p_Entities, String filePath, String fileName) {
        // 标记文件生成是否成功
        boolean flag = true;

        try {

            File pathFile = new File(filePath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            // 含文件名的全路径
            String fullPath = filePath + File.separator + fileName;

            File file = new File(fullPath);
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file = new File(fullPath);
            file.createNewFile();

            // 格式化浮点数据
            NumberFormat formatter = NumberFormat.getNumberInstance();
            formatter.setMaximumFractionDigits(10); // 设置最大小数位为10

            // 格式化日期数据
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

            // 遍历输出每行
            PrintWriter pfp = new PrintWriter(file, "UTF-8"); //设置输出文件的编码为utf-8
            int i = 0;
            for (String entity : p_Entities) {
                if (i > 0) {
                    pfp.print(";");
                }
                pfp.print(entity);
                i = i + 1;
            }
            pfp.close();
            log.info("生成文件:" + fileName);
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return flag;
    }

    /**
     * 功能：Java读取txt文件的内容
     * 步骤：1：先获得文件句柄
     * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     * 4：一行一行的输出。readline()。
     * 备注：需要考虑的是异常情况
     *
     * @param filePath
     */
    public String readTxtFile(String filePath) {
        StringBuilder result = new StringBuilder();
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    result.append(System.lineSeparator() + lineTxt);
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            result = new StringBuilder();
            e.printStackTrace();
        }
        return result.toString();
    }


    /**
     * 记录日志在文件
     *
     * @param zbhList
     * @param startTime
     * @param endTime
     * @param filePath
     */
    public void recordData(List<String> zbhList, String startTime, String endTime, String filePath) {

        //文件路径不存在则进行创建
        File pathFile = new File(filePath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        String filename = "filename_";
        String extension = ".txt";
        String fullFilename = filename + DateUtil.dateCoverYearMonthDay() + extension;
        // 含文件名的全路径
        String fullPath = filePath + File.separator + fullFilename;

        File file = new File(fullPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String content = JSON.toJSONString(zbhList);
        StringBuilder sb = new StringBuilder();
        sb.append(startTime).append("--").append(endTime).append(":").append(content);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fullPath, true))) {
            writer.write(sb.toString());
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
